package com.garlic.face.jlf.ui;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.transaction.constances.CommonConstant;
import com.garlic.face.jlf.utils.LogFileUtil;
import com.garlic.face.jlf.utils.PrintUtil;
import com.garlic.face.jlf.utils.ToastUtils;
import com.printer.sdk.PrinterConstants;
import com.printsdk.usbsdk.UsbDriver;


import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by shiyanqi on 18/8/23.
 */

public class PrintLogActivity extends BaseActivity{
	private static final String TAG = "PrintLogActivity";
	private Button log;
	private static UsbDriver mUsbDriver;
	private static UsbDevice mUSBDevice;
	private ArrayList<UsbDevice> deviceList;
	private MyHandler myHandler = new MyHandler(this);
	public static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";

	private static class MyHandler extends Handler {
		private WeakReference<PrintLogActivity> mLogActivityWeak;

		public MyHandler(PrintLogActivity printLogActivity) {
			mLogActivityWeak = new WeakReference<>(printLogActivity);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case PrinterConstants.Connect.SUCCESS:
					String connectOk = "USE打印机-连接成功";
					Log.d(TAG, connectOk);
					LogFileUtil.writeLog(connectOk);
					break;
				case PrinterConstants.Connect.FAILED:
					String connectFaile = "USB打印机-连接失败";
					ToastUtils.toastShow(connectFaile, Toast.LENGTH_SHORT);
					Log.d(TAG, connectFaile);
					LogFileUtil.writeLog(connectFaile);
					break;
				case PrinterConstants.Connect.CLOSED:
					String connectClose = "USB打印机-连接关闭";
					ToastUtils.toastShow(connectClose, Toast.LENGTH_SHORT);
					Log.d(TAG, connectClose);
					LogFileUtil.writeLog(connectClose);
					break;
				case PrinterConstants.Connect.NODEVICE:
					String connectNo = "USB打印机-没有连接";
					ToastUtils.toastShow(connectNo, Toast.LENGTH_SHORT);
					Log.d(TAG, connectNo);
					LogFileUtil.writeLog(connectNo);
					break;
				case CommonConstant.NET_STATE_UNCONNECT:
					String netStateUnconnect = "网络错误";
					ToastUtils.toastShow(netStateUnconnect, Toast.LENGTH_SHORT);
					Log.d(TAG, netStateUnconnect);
					LogFileUtil.writeLog(netStateUnconnect);
					break;
				default:
					break;
			}
		}
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_print_log);
		init();
	}

	private void init() {
		UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
		usbAutoConn(manager);
		log = findViewById(R.id.click);
		log.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
//				PrintUtil.printLog(PrintLogActivity.getmUSBDevice(), PrintLogActivity.getmUsbDriver());
			}
		});
	}

	/**
	 * 打开自动连接打印机
	 *
	 * @param manager
	 */
	public void usbAutoConn(UsbManager manager) {
		doDiscovery(manager);
		if (deviceList.isEmpty()) {
			ToastUtils.toastShow("USB打印机没有连接", Toast.LENGTH_SHORT);
			return;
		}
		mUSBDevice = deviceList.get(0);
		if (mUSBDevice == null) {
			String connectFaile = "USE打印机-连接失败";
			Log.d(TAG, connectFaile);
			LogFileUtil.writeLog(connectFaile);
			ToastUtils.toastShow(connectFaile, Toast.LENGTH_SHORT);
			return;
		}
		// 美松
		mUsbDriver = new UsbDriver(manager, this);
		LogFileUtil.writeLog("deviceName: " + mUSBDevice.getDeviceName());
		Log.d(TAG, mUSBDevice.getDeviceName());
		UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		try {
			if (mUsbManager != null) {
				if (mUsbManager.hasPermission(mUSBDevice)) {
					openUsbConnect();
				} else {
					// 没有权限询问用户是否授予权限
					PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
					IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
					filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
					filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
					registerReceiver(mUsbReceiver, filter);
					mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
				}
			} else {
				String msg = "USBManager空指针";
				Log.d(TAG, msg);
				LogFileUtil.writeLog(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String msg = "USB-Service空指针";
			Log.d(TAG, msg);
			LogFileUtil.writeLog(msg);
		}
	}

	/**
	 * 打开USB打印机
	 */
	private void openUsbConnect() {
		mUsbDriver.usbAttached(mUSBDevice);
		boolean b = mUsbDriver.openUsbDevice(mUSBDevice);
	}

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					unregisterReceiver(mUsbReceiver);
					UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
					if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
							&& mUSBDevice.equals(device)) {
						openUsbConnect();
					} else {
						myHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
					}
				}
			}
		}
	};

	/**
	 * 没有则自动获取设备
	 *
	 * @param manager
	 */
	private void doDiscovery(UsbManager manager) {
		HashMap<String, UsbDevice> devices = manager.getDeviceList();
		deviceList = new ArrayList<UsbDevice>();
		for (UsbDevice device : devices.values()) {
			if (PrintUtil.isUsbPrinter(device)) {
				Log.d(TAG, "doDiscovery: " + device.getDeviceName());
				deviceList.add(device);
			}
//            if (USBPort.isUsbPrinter(device)) {
//                deviceList.add(device);
//            }
		}
	}

	public static UsbDevice getmUSBDevice() {
		return mUSBDevice;
	}
	public static UsbDriver getmUsbDriver() {
		return mUsbDriver;
	}
}
